

<template>
  <div class="swiper-container">
    <swiper class="swiper-box" direction="vertical" :slides-per-view="1" :space-between="50" @swiper="onSwiper" @slideChange="onSlideChange">
      <swiper-slide class="swiper-item" v-for="(video, index) in videoList" :key="index">
        <video ref="videoRefs" width="100%" autoplay muted controls loop preload="metadata" :poster="`https://app.kpgansu.cn${video.pictureUrl}`">
          <source :src="`https://app.kpgansu.cn${video.videoUrl}`">
          您的浏览器不支持视频标签。
        </video>
        <div class="video-info">
          <div class="content">
            <div class="username"> {{ video.accountName|| '用户' }}</div>
            <div class="description">{{video.digest ||'-'}}</div>
          </div>
        </div>
        <div class="toolbar">
          <!-- 头像 + 添加按钮 -->
          <div class="avatar-ctn mb2r">
            <img class="avatar" :src="`https://app.kpgansu.cn${video.headPhoto}`" alt="" v-if="video.headPhoto" @click="togglekup(video,index)">
            <img class="avatar" src="@/assets/images/moren.png" alt="" v-else @click="togglekup(video,index)">
            <div :class="{'options': !video.isFans,'option': video.isFans}" @click="handleFollow(video,index)">
              <img class="no" src="@/assets/icon/add-light.png" alt="" v-if="!video.isFans">
              <img class="yes" src="@/assets/icon/ok-red.png" alt="" else>
            </div>
          </div>
          <!-- 点赞 -->
          <div class="love mb2r">
            <div class="love-icon" @click="handleLike(video, index)">
              <van-icon size="35px" name="like" :class="{ 'isLiked': video.isLike }" />
            </div>
            <!-- 点赞数 -->
            <div class="likeCount">{{video.contentLike || 0}}</div>
          </div>
          <!-- 评论 -->
          <div class="love mb2r">
            <div class="love-icon">
              <van-icon size="35px" name="chat" @click="toggleComment(video,index,'')" />
            </div>
            <!-- 评论数 -->
            <div class="likeCount">{{ video.commentNum || 0 }}</div>
          </div>
          <!-- 收藏 -->
          <div class="love mb2r">
            <div class="love-icon" @click="handleStar(video, index)">
              <van-icon size="35px" name="star" :class="{ 'isStar': video.isCollect==1 }" />
            </div>
            <!-- 收藏数 -->
            <div class="likeCount">{{ video.collectNum || 0 }}</div>
          </div>
          <!-- 分享 -->
          <div class="love mb2r">
            <div class="love-icon">
              <van-icon size="35px" name="share" @click="toggleShare(video)" />
            </div>
            <!-- 分享数 -->
            <div class="likeCount">分享</div>
          </div>
        </div>
      </swiper-slide>

    </swiper>
    <!-- <MyEmpty emptyText="暂无相关内容" v-else /> -->
    <!-- 评论弹框 -->
    <van-popup v-model:show="comment.showPopup" round overlay position="bottom" closeable close-icon="clear" @click-close-icon="onClickCloseIcon" style="height: 60%;">
      <div class="comment">
        <!-- 标题 -->
        <div class="comment-title">评论 <span>({{comment.total || 0}})</span></div>
        <!-- 评论列表 -->
        <van-list v-model:loading="comment.loading" :finished="comment.finished" finished-text="—— 我是有底线的 ——" @load="onLoad" offset="20" loading-text="正在加载">
          <template v-if="comment.contentlist.length>0">
            <div class="comment-content" v-for="(item,index) in comment.contentlist" :key="index">
              <div class="comment-content-item">
                <!-- 评论头像 -->
                <div class="comment-content-item-left">
                  <img :src="`https://app.kpgansu.cn${item.appId}`" alt="" v-if="item.appId">
                  <img src="@/assets/images/moren.png" alt="" v-else>
                </div>
                <!-- 评论内容 网名 -->
                <div class="comment-content-item-right">
                  <div class="comment-content-item-right-name">{{item.commentUserName || '暂无数据'}}</div>
                  <div class="comment-content-item-right-content">{{ item.content || '暂无数据'}}</div>
                  <div class="comment-content-item-right-time">{{timeFetter(item.ctime) || '暂无数据'}} <span @click="reply(item,index)">回复</span></div>
                </div>
              </div>
              <div v-for="(reply,index) in item.replyList" :key="index">
                <!-- 上半部分回复 -->
                <div class="comment-content-more" v-if="item.replyList.length ==1 && item.replyLists.length==0">
                  <!-- 折叠面板内容 -->
                  <div class="comment-content-items">
                    <!-- 评论头像 -->
                    <div class="comment-content-item-left">
                      <img :src="`https://app.kpgansu.cn${reply.appId}`" alt="" v-if="reply.appId">
                      <img src="@/assets/images/moren.png" alt="" v-else>
                    </div>
                    <!-- 评论内容 网名 -->
                    <div class="comment-content-item-right commentwidth">
                      <div class="comment-content-item-right-name commentfize">{{ reply.commentUserName || '暂无数据' }}</div>
                      <div class="comment-content-item-right-content  commentcontent">{{ reply.content || '暂无数据' }}</div>
                    </div>
                  </div>
                </div>
                <transition-group name="slide-fade" tag="div">
                  <!-- 下半部分回复 -->
                  <div class="comment-content-more" v-for="(item,index) in item.replyLists" :key="index">
                    <!-- 折叠面板内容 -->
                    <div class="comment-content-items">
                      <!-- 评论头像 -->
                      <div class="comment-content-item-left">
                        <img :src="`https://app.kpgansu.cn${item.appId}`" alt="" v-if="item.appId">
                        <img src="@/assets/images/moren.png" alt="" v-else>
                      </div>
                      <!-- 评论内容 网名 -->
                      <div class="comment-content-item-right commentwidth">
                        <div class="comment-content-item-right-name commentfize">{{ item.commentUserName || '暂无数据' }}</div>
                        <div class="comment-content-item-right-content  commentcontent">{{ item.content || '暂无数据' }}</div>
                      </div>
                    </div>
                  </div>
                </transition-group>
              </div>
              <div class="show-more comment-content-items">
                <div @click="toggleShowMore(item,index)" v-if="item.replyList.length>=1">
                  {{ item.showMore ? '收起' : `全部${ item.totalReply||0 }条评论` }}
                  <span>
                    <van-icon name="arrow-up" v-if="item.showMore" />
                    <van-icon name="arrow-down" v-else />
                  </span>
                </div>
              </div>
            </div>
          </template>
          <MyEmpty v-else />
        </van-list>
        <!-- 发布评论 -->
        <div class="comment-content-footer">
          <van-search show-action left-icon="edit" v-model="comment.value" placeholder="发表想法">
            <template #action>
              <div class="button" @click="onClickButton">发送</div>
            </template>
          </van-search>
        </div>
      </div>
    </van-popup>
    <!-- 回复弹框 -->
    <van-popup v-model:show="comment.showPopupReply" overlay position="bottom">
      <!-- 发布评论 -->
      <div class="comment-content-footer">
        <van-search show-action left-icon="edit" v-model="comment.valueReply" :placeholder="comment.placeholderReply">
          <template #action>
            <div class="button" @click="onClickButtonReply">发送</div>
          </template>
        </van-search>
      </div>
    </van-popup>
    <van-toast></van-toast>
  </div>

</template>
<script setup>
// 导入vant库的showToast函数，用于显示短暂的提示信息
import { showToast } from 'vant'
// 导入Swiper组件和SwiperSlide组件，用于创建轮播图
import { Swiper, SwiperSlide } from 'swiper/vue';
// 导入Swiper的CSS样式，确保轮播图的正确显示
import 'swiper/css';
// 导入工具函数，包括从URL中提取ID、防抖和时间限制函数
import { extractIdsFromUrl, debounce, timeFetter } from "@/tools/tool";
// 导入用户状态的Vuex模块，用于管理用户信息和状态
import { useUserStore } from '@/store/index'
// 导入服务端API接口，用于与服务器进行数据交互
import { serveAPI } from "@/api/serve";
// 使用自定义组件
import MyEmpty from '@/components/empty/empty.vue'


// 视频数据列表
const videoList = ref([]);
const videoRefs = ref(null);
// 用于存储各种交互状态的数据对象
const data = reactive({
  pageNo: 1,//当前页码，用于分页加载数据
  pageSize: 10,//每页显示的数据数量
  total: 0,  // 总数据量,
  ListValue: {}, // 保存当前跳转人信息
  listIndex: '',//当前跳转的索引
});
const comment = reactive({
  value: '',//发布评论内容,
  currentIndex: '',
  loading: false,//表示数据是否正在加载中
  finished: false, //表示是否已经加载完所有数据
  pageNo: 1,//当前页码，用于分页加载数据
  pageSize: 10,//每页显示的数据数量
  contentlist: [], // 内容列表，存储加载的数据
  total: 0, // 总数据量，用于判断是否已经加载完所有数据
  showPopup: false,// 控制评论弹窗显示状态
  showMore: false, // 控制评论列表显示状态
  preserve: {},//保存当前评论人信息
  placeholderReply: ref(''),//回复人 placeholder
  showPopupReply: false,//控制回复弹窗显示状态
  valueReply: '',//回复评论内容,
  controlCommentListShow: false,//控制评论列表回复
  replyData: {},//保存当前回复人信息
  toastShow: true,//控制toast显示状态
})




// 在组件挂载时添加事件监听器
onMounted(() => {
  // 添加 visibilitychange 事件监听器
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  // 移除 visibilitychange 事件监听器
  // document.removeEventListener('visibilitychange', handleVisibilityChange);
});

// 处理 visibilitychange 事件的函数
const handleVisibilityChange = async () => {
  // 获取用户信息
  let token;
  await lightAppJssdk.user.getUserInfo({
    success: async userdata => {
      console.log(userdata, '获取用户信息')
      if (userdata == '未登录') {
        token = ''
      } else { // 已经登录
        if (userdata == '用户拒绝授权') {
          lightAppJssdk.navigation.close({})
        } else {
          token = JSON.parse(userdata).token
          // 更新可见性状态
          let params = {
            accountId: data.ListValue.accountId,
            token: token
          }
          await serveAPI.queryList('gsskxjsxhdyh', 'queryFnasInfo', params).then(res => {
            console.log(res, data.listIndex, '查看关注状态')
            if (res.code == 200 && res.success) {
              // videoList.value[data.listIndex].isFans = res.data.data
            } else {
              return
            }
          }).catch((err) => {
            return err
          })
        }
      }
    },
    fail: () => {
      token = ''
    }
  })

}


/**
 * handleFollow - 关注操作
 * 无参数
 * 无返回值
 */
const handleFollow = (value, index, token) => {
  videoList.value[index].isFans = !videoList.value[index].isFans
}

/**
 * handleLike - 点赞操作
 * value, index
 */
const handleLike = (value, index) => {
  videoList.value[index].isLike = !videoList.value[index].isLike
  videoList.value[index].contentLike = videoList.value[index].isLike ? videoList.value[index].contentLike += 1 : videoList.value[index].contentLike -= 1
}
/**
 * handleStar - 收藏操作
 * 无参数
 * 无返回值
 */
const handleStar = (value, index) => {
  videoList.value[index].isCollect = videoList.value[index].isCollect == 0 ? 1 : 0
  videoList.value[index].collectNum = videoList.value[index].isCollect == 0 ? videoList.value[index].collectNum -= 1 : videoList.value[index].collectNum += 1
};
// 切换评论按钮的状态
const toggleComment = (item, index, type) => {
  comment.contentlist = []
  console.log(item, index, type, '切换评论按钮的状态')
  comment.preserve = item // 保存信息
  comment.showPopup = true
};
// 切换分享按钮的状态
const toggleShare = (value) => {
  showToast({ message: '该功能正在开发中！', duration: 3000 });
};

// 获取视频列表数据
const getVideoList = async (type) => {
  let params = {
    token: '',
    channelId: 'ZFBRz2wABROGQUWGig8bu', // 频道ID
    currentContentId: 'zx9809tnEGYqENDog8ZrN',// 文章ID
    pageNo: data.pageNo,
    pageSize: data.pageSize,
  }
  console.log(params, '获取视频列表params')
  await serveAPI.queryList('gsskxjsxhdyh', 'jsmcvideolist', params).then(res => {
    console.log(res, '获取视频列表')
    if (res.code == 200 && res.success && res.data.data.videoList.length > 0) {
      data.total = res.data.data.videoNum
      if (type === 'add') {
        videoList.value = videoList.value.concat(res.data.data.videoList)
      } else {
        videoList.value = res.data.data.videoList
      }
      if (videoList.value.lengthl > data.tota) {
        data.pageNo = 1
      }

    } else {
      videoList.value = []
    }
  }).catch((err) => {
    return err
  })
};

// 初始化时获取视频列表
getVideoList();

/**
 * onClickButton - 发送
 */
const onClickButton = async () => {
  showToast({ message: '该功能正在开发中！', duration: 3000 });
}
// 回复评论
const reply = (item, index) => {
  showToast({ message: '该功能正在开发中！', duration: 3000 });
};
/**
 * onClickButtonReply - 回复评论发送
 */
const onClickButtonReply = async () => {
  showToast({ message: '该功能正在开发中！', duration: 3000 });
}

// 跳转到科普号主页
const togglekup = (value, index) => {
  showToast({ message: '该功能正在开发中！', duration: 3000 });
}
const onSwiper = (swiper) => {
  console.log(swiper);
};
const onSlideChange = (swiper) => {
  console.log(swiper, 'slide change');
  // 获取当前激活的slide索引
  const activeIndex = swiper.activeIndex;
  // 获取上一个slide索引
  const previousIndex = swiper.previousIndex;
  // 关闭上一个视频的声音
  const previousVideo = videoRefs.value[previousIndex];
  if (previousVideo) {
    previousVideo.muted = true;
  }
  // 开启当前视频的声音
  const currentVideo = videoRefs.value[activeIndex];
  if (currentVideo) {
    currentVideo.muted = false;
  }

  if (activeIndex % 10 == 8) {
    if (videoList.value.length > data.total) {
      data.pageNo = 1
      getVideoList()
    } else {
      data.pageNo += 1
      getVideoList('add')
    }
  } else {
    return
  }
};
// 点击关闭图标时触发
const onClickCloseIcon = () => {
  console.log('click-close-icon');
  comment.showPopup = false
  comment.pageNo = 1
};
</script>
<style lang="less" scoped>
/* 添加一些基本样式，根据需求自行调整 */
.swiper-container {
  width: 100%;
  height: 100vh;
  background: #000;
  position: relative;
  .swiper-box {
    width: 100%;
    height: 100vh;
  }
  .swiper-item {
    height: 100vh;

    video {
      height: 100vh;
    }
  }
  .video-info {
    position: absolute;
    bottom: 65px;
    left: 20px;
    display: flex;
    align-items: center;
    .content {
      color: #fff;
      text-align: left;
      .username {
        font-size: 17px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .description {
        font-size: 13px;
      }
    }
  }
}
.toolbar {
  position: absolute;
  bottom: 45px;
  right: 10px;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar-ctn {
    position: relative;
    .avatar {
      width: 45px;
      height: 45px;
      border: 3px solid white;
      border-radius: 50%;
    }
    .option {
      position: absolute;
      width: 18px;
      height: 18px;
      display: flex;
      position: absolute;
      left: 0;
      right: 0;
      bottom: -5px;
      border-radius: 50%;
      margin: auto;
      justify-content: center;
      align-items: center;
      background: #fff;
      img {
        position: absolute;
        width: 14px;
        height: 14px;
        transition: all 1s;
      }
    }
    .options {
      position: absolute;
      border-radius: 50%;
      margin: auto;
      left: 0;
      right: 0;
      bottom: -5px;
      background: red;
      width: 18px;
      height: 18px;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        position: absolute;
        width: 14px;
        height: 14px;
      }
      .yes {
        opacity: 0;
        transform: rotate(-180deg);
      }
    }
  }
  .love {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .likeCount {
      font-size: 12px;
    }
  }
}
.comment {
  background: #fff;
  display: flex;
  flex-direction: column;
  ::v-deep(.van-list) {
    max-height: 390px;
    padding-bottom: 60px;
    flex: 1;
    overflow: auto;
  }
  .comment-title {
    position: fixed;
    width: 100%;
    padding: 0 12px;
    font-size: 17px;
    background: #fff;
    height: 45px;
    line-height: 50px;
    span {
      margin-left: 6px;
    }
  }
  .comment-content:nth-child(1) {
    padding-top: 52px;
  }

  .comment-content {
    ::v-deep(.van-icon) {
      z-index: -999;
    }
    border-bottom: 0.5px solid #e5e5e5;
    .show-more {
      font-size: 12px;
      color: #4972e2;
    }
    .comment-content-items {
      display: flex;
      padding: 6px 66px;
      .comment-content-item-left {
        width: 22px;
        height: 22px;
        border: 50%;
        margin-right: 10px;
        img {
          border-radius: 50%;
        }
      }
    }
    .comment-content-item {
      display: flex;
      padding: 12px;
      .comment-content-item-left {
        width: 44px;
        height: 44px;

        margin-right: 10px;
        img {
          border-radius: 50%;
        }
      }
    }
    .commentwidth {
      width: 230px !important;
    }
    .commentfize {
      font-size: 10px !important;
    }
    .commentcontent {
      font-size: 12px !important;
    }
    .comment-content-item-right {
      width: 325px;

      .comment-content-item-right-name {
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
      }
      .comment-content-item-right-content {
        font-size: 15px;
        color: #333;
        margin-bottom: 12.5px;
      }
      .comment-content-item-right-time {
        font-size: 12px;
        color: #999;
        span {
          color: #666;
          margin-left: 16px;
        }
      }
    }
  }
  .comment-content-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 54px;
    .button {
      width: 54px;
      height: 32px;
      border-radius: 16px;
      background: #4972e2;
      color: #fff;
      text-align: center;
      line-height: 32px;
    }
  }
}
.mb2r {
  margin-bottom: 20px !important;
}

.isLiked {
  color: red !important;
}
.isStar {
  color: rgb(252, 179, 3) !important;
}
::v-deep(.van-search__content) {
  border-radius: 25px;
}
::v-deep(.van-popup__close-icon--top-right) {
  position: fixed;
  top: 42%;
}
::v-deep(.van-toast) {
  background: rgba(0, 0, 0, 0.5) !important;
}
</style>